<template>
    <div class="container">
      <TeacherSidebar />
      <div class="right-content">
        <main class="main">
          <div class="student-list">
            <div class="fixed-header">
              <div class="student-list-header">
                <h2>学生名单</h2>
              </div>
              <div class="button-row">
                <el-button type="primary" @click="dialogVisible = true">导入学生名单</el-button>
              </div>
            </div>
            <div class="student-list-content">
              <el-table 
                :data="tableData" 
                stripe 
                height="calc(100vh - 200px)"
                :header-cell-style="{ background: '#f5f7fa' }"
              >
                <el-table-column 
                  type="index" 
                  label="序号" 
                  width="70" 
                  fixed="left"
                  align="center"
                />
                <el-table-column prop="username" label="用户名" width="180" />
                <el-table-column prop="name" label="姓名" width="180" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </main>
      </div>
    </div>

    <!-- 添加导入弹窗 -->
    <el-dialog
      title="导入学生"
      v-model="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="upload-content">
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          accept=".xlsx"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>
        </el-upload>
        <div class="file-tip">支持XLSX文件</div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpload">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import TeacherSidebar from '@/components/TManageSidebar.vue';
  import { ref, onMounted } from 'vue';
  import * as XLSX from 'xlsx';
  import { uploadStudentList, getStudentList, deleteStudent } from '@/api/teacher'; // 添加 deleteStudent
  import { ElMessage } from 'element-plus';
  import { useRoute } from 'vue-router';

  const route = useRoute();
  const studentList = ref([]);

  const tableData = ref([]);

  const dialogVisible = ref(false);
  const uploadFile = ref(null);

  const handleFileChange = (file) => {
    const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                    file.raw.type === 'application/vnd.ms-excel';
    
    if (!isExcel) {
      ElMessage.error('只能上传 Excel 文件!');
      return false;
    }
    uploadFile.value = file.raw;
    return true;
  };

  const handleUpload = async () => {
    if (!uploadFile.value) {
      ElMessage.warning('请先选择文件');
      return;
    }

    try {
      const formData = new FormData();
      formData.append('file', uploadFile.value);
      const courseManageId = route.query.courseManageId || route.params.courseManageId;
      if (!courseManageId) {
        ElMessage.error('课程信息获取失败');
        return;
      }
      formData.append('courseManageId', courseManageId);
      
      const response = await uploadStudentList(formData);
      
      if (response.code === 0) {
        ElMessage.success('导入成功');
        dialogVisible.value = false;
        await fetchStudentList();
      } else {
        const errorMsg = response.message || '导入失败';
        if (errorMsg.includes('该课程已存在该学生')) {
          ElMessage.warning('文件中包含已存在的学生，请检查后重试');
        } else if (errorMsg.includes('用户不存在或课程不存在')) {
          ElMessage.error('导入失败：用户信息或课程信息无效');
        } else {
          ElMessage.error(errorMsg);
        }
      }
    } catch (error) {
      console.error('导入失败详情：', error.response?.data || error);
      ElMessage.error('导入失败，请检查文件格式是否正确');
    }
  };

  const fetchStudentList = async () => {
    try {
      const courseManageId = route.query.courseManageId || route.params.courseManageId;
      if (!courseManageId) {
        ElMessage.error('课程信息获取失败');
        return;
      }
      const res = await getStudentList(courseManageId);
      tableData.value = res.data;
    } catch (error) {
      console.error('获取学生列表失败:', error);
      ElMessage.error('获取学生列表失败');
    }
  };

  const handleDelete = async (row) => {
    try {
      await ElMessageBox.confirm('确认删除该学生吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      
      const res = await deleteStudent(row.teamId);
      if (res.success) {
        ElMessage.success('删除成功');
        await fetchStudentList();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error);
        ElMessage.error('删除失败');
      }
    }
  };

  // 在组件挂载时获取学生列表
  onMounted(() => {
    fetchStudentList();
  });
  </script>
  
  <style scoped>
  .container {
    display: flex;
    min-height: 100vh;
    justify-content: center;
    align-items: center;
  }

  .right-content {
    margin-left: 60px;
    flex: 1;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    padding: 20px;
  }

  .main {
    width: 100%;
  }

  .student-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    margin-top: 20px;
  }

  .student-list-header {
    display: flex;
    justify-content: flex-start;
    width: 80%;
    max-width: 1200px;
    margin-bottom: 10px;
    z-index: -1;
  }

  .student-list-header h2 {
    margin: 0;
    padding-left: 0;
  }

  .button-row {
    display: flex;
    justify-content: flex-end;
    width: 80%;
    max-width: 1200px;
    margin-bottom: 20px;
  }

  .fixed-header {
    position: sticky;
    top: 60px;
    background-color: white;
    width: 100%;
    z-index: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    margin: 0 20px;
    background: #fff;
    border-radius: 8px;
  }

  .student-list-content {
    display: flex;
    justify-content: center;
    width: 80%;
    max-width: 1200px;
    margin: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 2;
    background-color: #f5f7fa;
  }

  :deep(.el-table__fixed) {
    position: sticky !important;
    left: 0;
    z-index: 3;
  }

  .upload-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }

  .file-tip {
    color: #909399;
    font-size: 12px;
    margin-top: 10px;
    align-self: flex-start;
    margin-left: 20px;
  }

  :deep(.dialog-footer) {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  :deep(.el-upload) {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  </style>